package com.study6.mybatis.more.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author xuly
 * @title: DruidConfig
 * @projectName spring-boot
 * @description: TODO
 * @date 2019-07-2415:55
 **/
@Configuration
@MapperScan(basePackages = {"com.study6.mybatis.more.mapper.trade"},
        sqlSessionFactoryRef = "tradeSqlSessionFactory")
public class TradeDruidConfig {

    @Value("${spring.datasource.trade.mapper-locations}")
    private String tradelocations;
    @Value("${spring.datasource.trade.type-aliases-package}")
    private String typePackage;

    @ConfigurationProperties(prefix = "spring.datasource.trade")
    @Primary
    @Bean
    public DataSource tradeDruidDataSource() {
        return new DruidDataSource();
    }

    @Bean
    public SqlSessionFactory tradeSqlSessionFactory(
            @Qualifier("tradeDruidDataSource") DataSource tradeDruidDataSource
    ) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(tradeDruidDataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // 配置mapper文件位置
        sqlSessionFactoryBean.setTypeAliasesPackage(typePackage);
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(tradelocations));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "tradeSqlSessionTemplate")
    public SqlSessionTemplate tradeSqlSessionTemplate(@Qualifier("tradeSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
